import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);
  
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const Home = () => import('views/home/Home')
const Category = () => import('views/category/Category')
const Cart = () => import('views/cart/Cart')
const Profile = () => import('views/profile/Profile')
const Detail = () => import('views/detail/Detail')
// import Home from 'views/home/Home'
// import Category from 'views/category/Category'
// import Cart from 'views/cart/Cart'
// import Profile from 'views/profile/Profile'
// import Detail from 'views/detail/Detail'
const routes = [
  {
    path:'',
    redirect: '/home'
  },
  {
    path:'/home',
    meta:{
      title: '首页'
    },
    component:Home,
    beforeEnter: (to, from, next) => {
      // ...
      // console.log(to,from)
      document.title = to.meta.title
      next()
    }
  },
  {
    path:'/category',
    component:Category,
    meta:{
      title: '分类'
    },
    beforeEnter: (to, from, next) => {
      // ...
      // console.log(to,from)
      document.title = to.meta.title
      next()
    }
  },
  {
    path:'/cart',
    component:Cart,
    meta:{
      title: '购物车'
    },
    beforeEnter: (to, from, next) => {
      // ...
      // console.log(to,from)
      document.title = to.meta.title
      next()
    }
  },
  {
    path:'/profile',
    component:Profile,
    meta:{
      title: '我的'
    },
    beforeEnter: (to, from, next) => {
      // ...
      // console.log(to,from)
      document.title = to.meta.title
      next()
    }
  },
  {
    path:'/detail/:iid',
    component:Detail,
    meta:{
      title: '详情'
    },
    beforeEnter: (to, from, next) => {
      // ...
      // console.log(to,from)
      document.title = to.meta.title
      next()
    }
  }
]

const router = new VueRouter({
  routes,
  mode:'history'
})
// //在路由对象上 挂载路由导航守卫
// router.beforeEach((to,from,next) => {
//   //to 将要访问的路径
//   //from 代表从哪个路径跳转过来
//   //next 是一个函数，表示放行
//   //  1.next() 放行   2.next('/login') 强制跳转到login

//   if(to.path === '/cart') return next();//如果用户访问登录页，直接放行
//   const tokenStr = window.sessionStorage.getItem('token')//获取token
//   if(!tokenStr) return next('/cart')//如果没有token 则强制登录
//   next()//如果用户携带了 token 则放行
// })

export default router